import axios from 'axios'
import router from '@/router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const axiosInstance = axios.create({
    baseURL: 'http://localhost:8980/js',
    timeout: 10000
})

// 请求拦截器
axiosInstance.interceptors.request.use(
    config => {
        const token = localStorage.getItem('access-key')
        if (token) {
            config.headers['access-key'] = token
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
axiosInstance.interceptors.response.use(
    response => {
        // 检查是否有新的token
        const newToken = response.headers['new-access-token']
        if (newToken) {
            const userStore = useUserStore()
            userStore.updateToken(newToken)
        }
        
        // 检查响应状态
        if (response.data && response.data.code === 401) {
            // Token无效，需要重新登录
            const userStore = useUserStore()
            userStore.logout()
            ElMessage.error('登录已过期，请重新登录')
            return Promise.reject(new Error('Token expired'))
        }
        
        return response
    },
    error => {
        if (error.response) {
            const status = error.response.status
            if (status === 401) {
                // 未授权，清除token并跳转登录
                const userStore = useUserStore()
                userStore.logout()
                ElMessage.error('登录已过期，请重新登录')
            } else if (status === 403) {
                ElMessage.error('没有权限访问该资源')
            } else if (status >= 500) {
                ElMessage.error('服务器错误，请稍后重试')
            }
        } else if (error.code === 'ECONNABORTED') {
            ElMessage.error('请求超时，请检查网络连接')
        } else {
            ElMessage.error('网络错误，请检查网络连接')
        }
        return Promise.reject(error)
    }
)

// 导出 axios 实例
export { axiosInstance }
export default axiosInstance


